﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Nest;
using Polly;

namespace Web.Controllers
{
    public class HomeController : Controller
    {

        public ActionResult Index()
        {
            //try
            //{
            //    var t1 = Task.Run(() =>
            //    {
            //        return DbHelperSQL.Query("SELECT * FROM Cities");
            //    });

            //    var t2 = Task.Run(() =>
            //    {
            //        return DbHelperSQL.Query("SELECT * FROM Cities");
            //    });

            //    Task.WaitAll(t1, t2);

            //    Response.Write(t1.Result.Tables[0].Rows.Count.ToString());
            //    Response.Write(t2.Result.Tables[0].Rows.Count.ToString());
            //}
            //catch (Exception ex)
            //{
            //    throw;
            //}

            Session["user"] = "abcdafadafsafds";
            return View();
        }

        public ActionResult About()
        {

            //try
            //{
            //    var node = new Uri("http://localhost:9200");
            //    var settings = new ConnectionSettings(node).DefaultFieldNameInferrer((name) => name);
            //    var client = new ElasticClient(settings);

            //    //基本配置
            //    IIndexState indexState = new IndexState()
            //    {
            //        Settings = new IndexSettings()
            //        {
            //            NumberOfReplicas = 1,//副本数
            //            NumberOfShards = 5//分片数
            //        }
            //    };
            //    client.CreateIndex("test-index3", p => p.InitializeUsing(indexState).Mappings(m => m.Map<TestModel5>(mp => mp.AutoMap())));
            //}
            //catch (Exception e)
            //{
            //    ViewBag.Message = e.Message;
            //    Console.WriteLine(e);
            //    throw;
            //}

            var error = string.Empty;

            //var policy = Policy.Handle<Exception>()
            //    .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(5), (exception, retryCount) =>
            //    {
            //        error = $"{error};第{retryCount}次：{exception.Message}";
            //    });

            //var result = policy.ExecuteAsync(() => Test());
            //try
            //{
            //    var retryTwoTimesPolicy =
            //        Policy
            //            .Handle<Exception>()
            //            .WaitAndRetry(new[]
            //            {
            //                TimeSpan.FromSeconds(1),
            //                TimeSpan.FromSeconds(3),
            //                TimeSpan.FromSeconds(5),
            //                TimeSpan.FromSeconds(7)
            //            }, (ex, count) =>
            //            {

            //                error += string.Format("执行失败! 重试次数 {0}", count);
            //                error += string.Format("异常来自 {0}", ex.GetType().Name);
            //            });
            //    retryTwoTimesPolicy.Execute(() =>
            //    {
            //        Compute();
            //    });
            //}
            //catch (Exception e)
            //{
            //    Console.WriteLine(e);
            //    //throw;
            //}

            ViewBag.Message += "<br/>Your application description page." + error;

            return View();
        }

        static int Compute()
        {
            var a = 0;
            return 1 / a;
        }

        private async Task Test()
        {
            using (var httpClient = new HttpClient())
            {
                var response = httpClient.GetAsync("http://11news.cnblogs.com/Category/GetCategoryList?bigCateId=11&loadType=0").Result;
                await response.Content.ReadAsStringAsync();
            }
        }

        public ActionResult Contact()
        {
            //var node = new Uri("http://localhost:9200");
            //var settings = new ConnectionSettings(node).DefaultFieldNameInferrer((name) => name);
            //var client = new ElasticClient(settings);

            //client.Index(new TestModel5
            //{
            //    Id=1000,
            //    Name="liwei",
            //    Dic = "lw",
            //    State = 1,
            //    Deleted = false,
            //    AddTime = DateTime.Now,
            //    PassingRate = 105,
            //    Dvalue = 23.88
            //}, s => s.Index("test-index3").Type("TestModel5"));


            ViewBag.Message = "Your contact page.";

            return View();
        }
    }


    [ElasticsearchType(Name = "TestModel", IdProperty = "Id")]
    public class TestModel5
    {
        [Number(NumberType.Long, Name = "Id")]
        public long Id { get; set; }
        /// <summary>
        /// keyword 不分词
        /// </summary>
        [Keyword(Name = "Name", Index = true)]
        public string Name { get; set; }
        /// <summary>
        /// text 分词,Analyzer = "ik_max_word"
        /// </summary>
        [Text(Name = "Dic", Index = true)]
        public string Dic { get; set; }

        [Number(NumberType.Integer, Name = "State")]
        public int State { get; set; }

        [Boolean(Name = "Deleted")]
        public bool Deleted { get; set; }
        [Date(Name = "AddTime")]
        public DateTime AddTime { get; set; }

        [Number(NumberType.Float, Name = "PassingRate")]
        public float PassingRate { get; set; }

        [Number(NumberType.Double, Name = "Dvalue")]
        public double Dvalue { get; set; }
    }
}